/**
 * @description blog service
 */

const { Blog, User, BlogRelation } = require('../db/model')
const { formatBlog } = require('./_format')
const { INIT_CONTENT_IMAGE } = require('../utils/constant')
const {
  del,
  getKeys,
  get
} = require('../cache/_redis')
const {
  LIST_KEY_PREFIX,
  BLOG_TYPE
} = require('../utils/constant')
const Sequelize = require('sequelize')
const Op = Sequelize.Op
// const { getCacheCount } = require('../cache/blog')

/**
 * @description 写博客
 * @param {string} content
 * @param {string} userId
 * @param {string} image
 */
async function createBlog({ content, userId, image, title }) {
  const i = Math.round(Math.random() * 2)
  const type = BLOG_TYPE[i]
  const result = await Blog.create({
    userId,
    title,
    content,
    image: image ? image : INIT_CONTENT_IMAGE,
    isLike: false,
    comment: 0,
    isCollect: false,
    check: 0,
    type
  })
  return result.dataValues
}
/**
 * @description 获取博客列表
 * @param {number} pageIndex
 * @param {number} pageSize
 * @param {string} userName
 */
async function getBlogList({ pageIndex = 1, pageSize = 150, userId = null, title = null, type = 'new' }) {
  let whereObj = {}
  let blogWhere = {
    type
  }
  if (userId) {
    whereObj.userId = userId
  }
  if (title) {
    blogWhere.title = {
      [Op.like]: `%${title}%`
    }
  }

  const result = await Blog.findAndCountAll({
    where: blogWhere,
    offset: pageSize * (pageIndex - 1),
    limit: pageSize,
    order: [
      ['id', 'desc']
    ],
    include: [
      {
        model: User,
        attributes: ['userName', 'avatar'],
        where: whereObj
      }
    ]
  })
  console.log(result, 'jiekg')
  const count = result.count
  const blogList = result.rows.map(item => {
    const blog = item.dataValues
    blog.user = blog.user.dataValues
    return blog
  })
  const info = await get('userInfo')
  const id = info && info.userId

  const _blogList = blogList.map(async item => {
    // 文章被收藏、点赞数
    const collect = await BlogRelation.count({
      where: {
        contentId: item.id,
        isCollect: true
      }
    })
    const like = await BlogRelation.count({
      where: {
        contentId: item.id,
        isLike: true
      }
    })
    item.collect = collect
    item.like = like
    // 文章被当前登录者是否收藏、点赞
    const collectRes = await BlogRelation.count({
      where: {
        userId: id,
        contentId: item.id,
        isCollect: true
      }
    })
    const likeRes = await BlogRelation.count({
      where: {
        userId: id,
        contentId: item.id,
        isLike: true
      }
    })
    item.isLike = likeRes !== 0
    item.isCollect = collectRes !== 0
    return Promise.resolve(item)
  })
  const arr = await Promise.all(_blogList)

  return {
    count,
    pageSize,
    pageIndex,
    blogList: formatBlog(arr)
  }

}

/**
 * 获取博客详情
 * @param {string} id 
 */
async function getDetail({id, userId}) {
  const whereObj = {
    id: userId
  }
  const result = await Blog.findOne({
    where: {
      id
    },
    include: [{
      model: User,
      attributes: ['userName', 'avatar', 'tag'],
      where: whereObj
    }]
  })
  if (!result) {
    return result
  }
  const blogInfo = result.dataValues
  const res = formatBlog([blogInfo])
  return res[0]
}

/**
 * 收藏文章
 * @param {string} contentId
 * @param {string} userId
 */
async function addCollectBlog({ contentId, userId }) {
  const result = await BlogRelation.upsert({
    contentId,
    userId,
    isCollect: true
  }, {
    contentId,
    userId
  })

  const keys = await getKeys(`${LIST_KEY_PREFIX}*`)
  if (keys.length) {
    await del(keys)
  }
  return result.dataValues
}
/**
 * @description 取消收藏 
 * @param {string} contentId
 * @param {string} userId
 */
async function delCollectBlog({ contentId, userId }) {
  console.log(userId, 999888777)
  const result = await BlogRelation.update({
    isCollect: false
  }, {
    where: {
      contentId,
      userId
    }
  })

  const keys = await getKeys(`${LIST_KEY_PREFIX}*`)
  if (keys.length) {
    await del(keys)
  }
  return result > 0
}
/**
 * 点赞
 * @param {string} contentId
 * @param {string} userId
 */
async function addLikeBlog({ contentId, userId }) {
  const result = await BlogRelation.upsert({
    contentId,
    userId,
    isLike: true
  }, {
    contentId,
    userId
  })
  await Blog.update({
    isLike: true
  }, {
    where: {
      id: contentId
    }
  })
  const keys = await getKeys(`${LIST_KEY_PREFIX}*`)
  if (keys.length) {
    await del(keys)
  }
  return result.dataValues
}
/**
 * 取消点赞
 * @param {string} contentId
 * @param {string} userId
 */
async function delLikeBlog({ contentId, userId }) {
  const result = await BlogRelation.update({
    isLike: false
  }, {
    where: {
      contentId,
      userId
    }
  })
  await Blog.update({
    isLike: false
  }, {
    where: {
      id: contentId
    }
  })
  const keys = await getKeys(`${LIST_KEY_PREFIX}*`)
  if (keys.length) {
    await del(keys)
  }
  return result > 0
}

module.exports = {
  createBlog,
  getBlogList,
  getDetail,
  addCollectBlog,
  delCollectBlog,
  addLikeBlog,
  delLikeBlog
}